package controller;

import java.util.List;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import server.ClientState;
import server.IProtocolHandler;
import xml.Message;
import entity.DecisionLinesEvent;

public class AdminProduceReportController implements IProtocolHandler {

	@Override
	public Message process(ClientState state, Message request) {
		
		// Get a reference to the system
		entity.System system = entity.System.getInstance();
		
		// Get the values for the key and the event type
		Node reportRequest = request.contents.getFirstChild();
		NamedNodeMap reportMap = reportRequest.getAttributes();
		String key = reportMap.getNamedItem("key").getNodeValue();
		String type = reportMap.getNamedItem("type").getNodeValue();
		
		// If the key is invalid, return an error message
		if (!system.validateAdminKey(key)) {
			String response = Message.responseHeader(request.contents.getAttributes().getNamedItem("id")
					.getNodeValue(), "Invalid key");
			response += "<reportResponse></reportResponse></response>";
			return new Message(response);
		}
		
		// Initialize the response header
		String response = Message.responseHeader(request.contents.getAttributes().getNamedItem("id")
				.getNodeValue());
		response += "<reportResponse>";
		
		// Retrieve all events of the given type, adding them to the response (need a method in System)
		List<DecisionLinesEvent> events = system.getEvents(type);
		for (DecisionLinesEvent e : events) {
			response += "<entry id='" + e.getId() + "' type='" + e.getEventType() + "' behavior='" + e.getTurnType()
					+ "' question='" + e.getQuestion() + "' numChoices='" + e.getNumChoices() + "' numRounds='"
					+ e.getNumRounds() + "' created='" + e.getCreationDate().toString() + "' completed='" + e.isDone() + "' />";
		}
		
		// Close the response and return it
		response += "</reportResponse></response>";
		return new Message(response);
	}

}

/*
<!-- ReportRequest           -->
<!-- _______________________ -->

<!-- admin requests must pass in key to be authorized -->
<xs:element name='reportRequest'>
  <xs:complexType>
    <xs:attribute name='key'   type='xs:string' use='required'/>
    <xs:attribute name='type'  type='eventType' use='required'/>
  </xs:complexType>
</xs:element>

<xs:element name='reportResponse'>
  <xs:complexType>
    <xs:sequence>
      <xs:element ref='entry' minOccurs='0' maxOccurs='unbounded'/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
*/